package bookstore.service;

import bookstore.handle.Msg;
import bookstore.mapper.ShopCartMapper;
import bookstore.model.ShopCart;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.NamingEnumeration;
import java.util.List;

@Service
public class ShopCartService {

    @Autowired
    ShopCartMapper shopCartMapper;

    //添加一本书籍进购物车
    public Object addOneBookInCart(Integer userId, Integer bookId, Integer count) {
        if (userId == null || bookId == null) {
            return new Msg(0, "非法操作！");
        }
        if (count == null) {
            count = 1;
        }
        ShopCart shopCartOne = shopCartMapper.selectOne(new QueryWrapper<ShopCart>().eq("user_id", userId).eq("book_id", bookId));
        if (shopCartOne != null) {
            shopCartOne.setCount(shopCartOne.getCount() + count);
            shopCartMapper.updateById(shopCartOne);
            return new Msg(200, "添加购物车成功");
        } else {
            ShopCart shopCart = new ShopCart(userId, bookId, count);
            shopCartMapper.insert(shopCart);
            if (shopCart.getId() != null) {
                return new Msg(200, "添加购物车成功");
            } else {
                return new Msg(0, "添加购物车失败");
            }
        }

    }

    //删除购物车
    public Object delOneCart(Integer userId, String listBookId) {
        if (userId == null || listBookId == null) {
            return new Msg(0, "请选择有效的书籍后再试");
        }
        JSONArray jsonArray=JSONArray.fromObject(listBookId);
        Integer i = shopCartMapper.delete(new QueryWrapper<ShopCart>().eq("user_id", userId).in("book_id", jsonArray));
        return new Msg(200, "移除购物车成功", i);
    }

    //购物车数量+1/-1
    public Object addCartCount(Integer userId, Integer type, Integer bookId) {
        if (userId == null || type == null || bookId == null) {
            return new Msg(0, "请输入有效的信息后再试");
        }
        ShopCart shopCart = shopCartMapper.selectOne(new QueryWrapper<ShopCart>().eq("user_id", userId).eq("book_id", bookId));
        Integer count = shopCart.getCount();
        if (type == 1) {
            //增加
            shopCart.setCount(count + 1);
        } else {
            //减少
            if (count <= 1) {
                return new Msg(0, "数量不能再减少了");
            } else {
                shopCart.setCount(count - 1);
            }
        }
        Integer i = shopCartMapper.updateById(shopCart);
        if (i == 1) {
            return new Msg(200, "更新数据成功", i);
        } else {
            return new Msg(0, "更新数量失败");
        }
    }

}
